package com.hz.api.admin.adapter;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author liusu
 */
@Slf4j
public class ResultMessage extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf message = (ByteBuf) msg;
        ByteBuf newByteBuf = null;

        try {
            // 接收的内容已通过换行符切分
            byte[] bytes = new byte[message.readableBytes()];
            newByteBuf = message.readBytes(bytes);
            String result = new String(bytes);

            // 判断数据格式
            if (result.startsWith("PING:")) {
                // 1. PING消息
                String[] arr = result.substring(5).split(",");
                log.info("收到压测引擎心跳信息：{}", result);
            } else {
                // 2. 监控指标
                log.info("收到压测引擎监控数据：{}", result);
            }
        } catch (Exception e) {
            log.error("处理压测工具上报数据异常", e);
        } finally {
            //SimpleChannelInboundHandler会自动释放
            if (message.refCnt() > 0) {
                ReferenceCountUtil.release(message);
            }

            if (Objects.nonNull(newByteBuf) && newByteBuf.refCnt() > 0) {
                ReferenceCountUtil.release(newByteBuf);
            }
        }
    }
}
